/**
 * Created by xiewei on 11/13/15.
 */
var imgDir = 'img/';//图片路径
var leavingConfirm = false;//离开页面提示

var dtFmlTelNumText = $("#dtFmlTelNum");//（传入）电话号码
var dtFmlSNSNumText = $("#dtFmlSNSNum");//QQ号或微信号输入框
var applySelectIcon = $("#applySelectIcon");//QQ号或微信号切换按钮
var applySelection = $('#applySelection');//QQ号、微信号选择下拉框
var applySelQQ = applySelection.find('li:first');//QQ
var applySelWechat = applySelection.find('li:last');//wechat
var isQQ = 1;

var dtFmlNameText = $("#dtFmlName");//寄养家庭名称
var dtFmlRealNameText = $("#dtFmlRealName");//真实姓名
var dtFmlIDCodeText = $("#dtFmlIDCode");//寄养家庭主人身份证号
var dtFmlIDCardFile = $("#dtFmlIDCardFile");//身份证照片上传表单控件（隐藏）
var dtFmlIDCardImg = $("#dtFmlIDCardImg");//身份证照片上传按钮 预览框

var interviewDate = $("#interviewDate");//预约视频认证时间
var interviewTime = $("#interviewTime");//预约视频认证时间
var interviewDateTab = $("#interviewDateTab");//预约面试时间页面
var interviewTimeTab = $("#interviewTimeTab");//预约面试时间选择页面

var curCover = null;//当前打开的遮罩内容
var cover = $("#cover");//遮罩

var applyTreatyLink = $("#applyTreatyLink");//查看寄养家庭服务协议链接
var applyTreatyCheck = $("#applyTreatyCheck");//寄养协议同意checkbox
var applyTreaty = $("#applyTreaty");//协议
var treatyCloseBtn = $("#treatyClose");//关闭协议按钮

var login = $('#login');//登陆框
var loginCloseBtn = $('#loginClose');//关闭登陆框按钮

var applySubmit = $("#applySubmit");//提交申请按钮

//申请寄养家庭信息
var applyFamilyData = {
    idcard: '',
    idcardPic: '',
    interviewDate: '',
    interviewTime: '',
    name: '',
    trueName: '',
    userId: '',
    qq: '',
    wechat: '',
    session: ''
}
//上传图片
var imgData = {
    session: '',
    type: '',
    userId: ''
}
//===================================操作===================================//
/**
 * QQ号或微信号码的输入切换
 */
$(document).click(function(){
    applySelection.addClass('hidden');
});
var snsNumTypeChange = function(e){
    e.stopPropagation();
    applySelection.toggleClass('hidden');
}
var snsNumTypeQQ = function(){
    isQQ = 1;
    dtFmlSNSNumText.attr("onkeypress","check(event)");
    dtFmlSNSNumText.attr("onkeyup","this.value=this.value.replace(/[^0-9]+/g,'')");
    dtFmlSNSNumText.attr("oninput","this.value=this.value.replace(/[^0-9]+/g,'')");
    applySelectIcon.prev().text('QQ');
    applySelection.addClass('hidden');
    applySelQQ.addClass('hidden');
    applySelWechat.removeClass('hidden');
}
var snsNumTypeWechat = function(){
    isQQ = 0;
    dtFmlSNSNumText.removeAttr("onkeypress");
    dtFmlSNSNumText.removeAttr("onkeyup");
    dtFmlSNSNumText.removeAttr("oninput");
    applySelectIcon.prev().text('微信');
    applySelection.addClass('hidden');
    applySelQQ.removeClass('hidden');
    applySelWechat.addClass('hidden');
}
/**
 * 点击同意\取消寄养协议
 * icon更换 value改变(0\1)
 */
treatyCheckImgs = {
    empty: 'icon_empty.png',
    agree: 'icon_agree.png'
}
var agreeTreaty = function(){
    var value = applyTreatyCheck.attr('value');
    if(value == 1){
        applyTreatyCheck.attr('src',imgDir+treatyCheckImgs.empty);
        applyTreatyCheck.attr('value',0);
    }else if(value == 0){
        applyTreatyCheck.attr('src',imgDir+treatyCheckImgs.agree);
        applyTreatyCheck.attr('value',1);
    }
}
hintIcons = {
    pass: 'icon_apply_pass.png',
    error: 'icon_apply_error.png'
}
var hintCombination = function(item,text,ifIcon){
    item.remove();
    if(ifIcon){
        $('<img>').attr('src',imgDir+hintIcons[ifIcon])
            .attr('alt',ifIcon).appendTo(item);
    }
    $('<label>').text(text).appendTo(item);

}
/**
 * 身份证照片上传预览效果
 */
window.URL = window.URL || window.webkitURL;
var idCardImgUpdate = function(event){
    var uploadImg = $("#dtFmlIDCardImg");
    var preHeight = uploadImg[0].height+2;//4是border的宽度
    var preWidth = uploadImg[0].width+2;
    var files = event.target.files;
    if(files.length==0){
        return false;
    }
    //在页面展示要上传的图片
    if(window.FileReader){
        var reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onload = function(){
            uploadImg.attr("src",this.result);
        }
    }else if(window.URL){
        uploadImg.attr("src",window.URL.createObjectURL(files[0]));
        uploadImg.onload = function(){
            window.URL.revokeObjectURL(this.src);
        }
    }else{//IE
        dtFmlIDCardFile.select();
        dtFmlIDCardFile.blur();
        var fileSrc = document.selection.createRange().text;
        document.selection.empty();
        uploadImg.attr("src",fileSrc);
    }
    //图片大小自适应
    var getImgNaturalSize = function(){
        var imgHeight = uploadImg[0].naturalHeight;
        var imgWidth = uploadImg[0].naturalWidth;
        if(imgHeight==0 || imgWidth==0){
            window.setTimeout(getImgNaturalSize,100);
        }else{
            //调整图片位置
            if(imgWidth/imgHeight > preWidth/preHeight){
                var height = imgHeight*(preWidth/imgWidth);
                uploadImg.css({
                    width: preWidth,
                    height: height,
                    border: '1px dashed #c9c9c9'
                    //marginTop: preHeight/2-height/2,
                    //marginLeft: 0
                });
            }else{
                var width = imgWidth*(preHeight/imgHeight);
                uploadImg.css({
                    width: width,
                    height: preHeight,
                    border: '1px dashed #c9c9c9'
                    //marginTop: 0,
                    //marginLeft: preWidth/2-width/2
                });
            }
        }
    }
    getImgNaturalSize();
}
/**
 * 关闭遮罩 关闭协议\关闭登陆输入框\登陆完成
 */
var closeCoverContent = function(){
    cover.addClass('hidden');
    curCover.addClass('hidden');
}
/**
 * 开启遮罩 显示对应内容
 */
var openCoverContent = function(item){
    cover.removeClass('hidden');
    item.removeClass('hidden');
    curCover = item;
}
//===================================输入检查===================================//
/**
 * 手机号输入期间检查（只允许输入数字）
 */
function check(e){
    var keyCode = e.keyCode || event.keyCode;
    if (keyCode >= 48 && keyCode <= 57) {
        event.returnValue = true;
    }else {
        event.returnValue = false;
    }
}
/**
 * 手机号输入完成检查
 */
var telNumCheck = function(){
    var telNum = dtFmlTelNumText.val().trim();
    var hint = dtFmlTelNumText.parent().parent().find('div.hint');
    if(telNum=="" || telNum==null){
        hintCombination(hint,'手机号码不可为空');
    }else{
        //$.ajax({
        //    url: '',
        //    data: '',
        //    type: 'GET',
        //    dataType: 'json',
        //    success: function(res){
        //
        //    }
        //})
    }
}
/**
 * QQ/微信检查
 */
var snsNumCheck = function(){
    var snsNum = dtFmlSNSNumText.val().trim();
    if(snsNum=="" || snsNum==null){
        applySelection.parent().next().next().children('label').text("微信和QQ必填一项，以用于视频认证");
        dtFmlSNSNumText.focus();
        return false;
    }else{
        if(isQQ == 1){
            applyFamilyData.qq = dtFmlSNSNumText.val();
        }else{
            applyFamilyData.wechat = dtFmlSNSNumText.val();
        }
        return true;
    }
}
/**
 * 寄养家庭名称检查
 * @param value
 */
var familyNameCheck = function(){
    var value = dtFmlNameText.val().trim();
    //家庭名称名称为中文、英文、数字
    var reg = /[\u4e00-\u9fa5|a-zA-Z|0-9]/;
    if(value=="" || value==null){
        showMessageAlert("请填写寄养家庭名称");
        dtFmlNameText.focus();
        return false;
    }else if(!reg.test(value)){
        showMessageAlert("寄养家庭名称不可输入特殊符号");
        dtFmlNameText.focus();
        return false;
    }
    applyFamilyData.name = value;
    return true;
}
/**
 * 用户真实姓名检查
 * @param value
 */
var trueNameCheck = function(){
    var value = dtFmlRealNameText.val().trim();
    //用户真实姓名只能是中文和英文
    var reg = /[\u4e00-\u9fa5|a-zA-Z]/;
    if(value=="" || value==null){
        showMessageAlert("请填写真实姓名");
        dtFmlRealNameText.focus();
        return false;
    }else if(!reg.test(value)){
        showMessageAlert("真实姓名不可输入特殊符号");
        dtFmlRealNameText.focus();
        return false;
    }
    applyFamilyData.trueName = value;
    return true;
}
/**
 * 身份证号码验证
 * @param value
 * @returns {boolean}
 */
var idCardCodeCheck = function(){
    var value = dtFmlIDCodeText.val().trim();
    var IDCardReg15 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
    var IDCardReg18 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;;
    if(value=="" || value==null){
        showMessageAlert("请输入身份证号码");
        //dtFmlIDCodeText.focus();
        return false;
    }else if(value.length<15 || !(IDCardReg15.test(value)||IDCardReg18.test(value)) ){
        showMessageAlert("请填写正确的身份证号");
        //dtFmlIDCodeText.focus();
        return false;
    }
    applyFamilyData.idcard = value;
    return true;
}
/**
 * 身份证照片验证
 */
var idCardImgCheck = function(){
    var imgSrc = $('#dtFmlIDCardImg').attr('src');
    if(imgSrc=="" || imgSrc==null){
        showMessageAlert("请上传身份证照片");
        return false;
    }else{
        return true;
    }
}
/**
 * 同意协议勾选检查
 */
var fosterTreatyCheck = function(){
    var ifChecked = applyTreatyCheck.attr("value");
    if(ifChecked == '1'){
        return true;
    }else{
        showMessageAlert("请确定同意《双方寄养服务协议》");
        return false;
    }
}

//===================================提交===================================//
/**
 * 提交申请
 */
var submitInfoCheck = function(){
    if(!familyNameCheck()){
        return false;
    }else if(!snsNumCheck()){
        return false;
    }else if(!trueNameCheck()){
        return false;
    }else if(!idCardCodeCheck()){
        return false;
    }else if(!idCardImgCheck()){
        return false;
    }else if(!orderDateAndTime()){
        return false;
    }else if(!fosterTreatyCheck()){
        return false;
    }
    //提交图片
    imgData.type = '5';
    var uploadData = paramCoding(imgData);
    $.ajaxFileUpload({
        url:'/dog2/attach/uploadAttach',
        secureuri: false,
        fileElementId: 'dtFmlIDCardFile',//file标签的id
        dataType: 'json',
        data: uploadData,
        success: function (res) {
            if(res.respCode){
                applyFamilyData.idcardPic = res.path;
                var data = paramCoding(applyFamilyData);
                //提交申请信息
                $.ajax({
                    url: "/dog2/appFamily/applyFamily",
                    data: data,
                    type: "POST",
                    dataType: 'json',
                    success: function(res){
                        if(res.respCode==0){
                            showMessageAlert('申请已提交');
                            window.open('success.html','_self');
                        }else{
                            showMessageAlert('提交失败：'+res.respDesc);
                        }
                    }
                });
            }else{
                showMessageAlert('图片提交失败：'+res.respDesc);
            }
        },
        error: function(){
            showMessageAlert('图片提交出错');
        }
    });

}

//===================================事件绑定===================================//
dtFmlTelNumText.on('blur',telNumCheck);//输入手机号检查
applyTreatyCheck.on("click",agreeTreaty);//点击同意\取消寄养协议
//dtFmlSubmitBtn.on("click",submitInfoCheck);//提交寄养家庭申请
applySelectIcon.on('click',snsNumTypeChange);//QQ 微信选择框
applySelQQ.on('click',snsNumTypeQQ);//QQ 微信选择框
applySelWechat.on('click',snsNumTypeWechat);//QQ 微信选择框
dtFmlIDCardImg.on("click",function(){
    dtFmlIDCardFile.click();
});
dtFmlIDCardFile.on("change",function(event){
    idCardImgUpdate(event);
});//上传身份证照片功能
interviewDate.on('click',function(){
    interviewDateTab.removeClass('hidden');
    docClickEvent(interviewDateTab);
});//面试日期选择
interviewTime.on('click',function(){
    interviewTimeTab.removeClass('hidden');
    docClickEvent(interviewTimeTab);
});//面试时间选择
treatyCloseBtn.on('click',closeCoverContent);//关闭遮罩 关闭对应的协议或登陆窗口
loginCloseBtn.on('click',closeCoverContent);//关闭遮罩 关闭对应的协议或登陆窗口
//查看协议
applyTreatyLink.on('click',function(){
    openCoverContent(applyTreaty);
});
//提交申请时 显示登录框
applySubmit.on('click',function(){
    openCoverContent(login);
});

/**
 * 离开页面提示
 */
$(window).on("beforeunload",function(){
    if(leavingConfirm){
        return "是否退出申请页面？您所填写的内容将不会保存";
    }
});

//===================================公共方法===================================//
/**
 *  页面添加点击事件 隐藏显示的日期\时间选择tab
 */
var docClickEvent = function(tab){
    $(document).on('click',function(e){
        if(!(e.target == tab.parent()[0]||$.contains(tab.parent()[0],e.target))){
            tab.addClass('hidden');
            $(document).off('click');
        }
    })
}
/**
 * 提示框
 */
var showMessageAlert = function(message){
    var mssAlert = $("#messageAlert");
    if(mssAlert.length==0 || mssAlert==undefined || mssAlert==null){
        mssAlert = $("<div>").attr("id","messageAlert")
            .addClass("message_alert");
        $("<p>").text(message)
            .css({width: message.length+"em"})
            .appendTo(mssAlert);
        $("body").append(mssAlert);
    }else{
        mssAlert.find("p").text(message)
            .css({width: message.length+"em"});
        mssAlert.show();
    }
    setTimeout(function(){
        mssAlert.hide();
    },1000);
}
/**
 * 加密方法
 * @param value
 * @returns {*}
 */
var code = function(value){
    if(value=="" || value==null){
        return "";
    }
    $.base64.utf8encode = true;
    if(value instanceof Object){
        value.jsonData = JSON.stringify(value.jsonData);
        value = JSON.stringify(value);
    }
    value = $.base64.encode(value);
    var middle = value.substring(1,3).split("").reverse().join("");
    var arr0 = value.charAt(0);
    var arr1 = value.substring(3,value.length);
    return $.base64.encode(arr0.concat(middle.concat(arr1)));
}
/**
 * JSON数据的参数分别加密
 * @param data
 * @returns {{}}
 */
var paramCoding = function(data){
    var codedData = {};
    $.each(data,function(key,value){
        if(key=='file'){
            codedData[key] = value;
        }else{
            codedData[key] = code(value);
        }
    });
    return codedData;
}
